package com.lxw.manage.course.service;

import com.alibaba.fastjson.JSON;
import com.lxw.framework.domain.cms.CmsPage;
import com.lxw.framework.domain.cms.response.CmsPageResult;
import com.lxw.framework.domain.course.*;
import com.lxw.framework.domain.course.ext.CourseView;
import com.lxw.framework.domain.course.ext.TeachplanNode;
import com.lxw.framework.domain.course.response.CoursePublishResult;
import com.lxw.framework.exception.ExceptionCast;
import com.lxw.framework.model.response.CommonCode;
import com.lxw.framework.model.response.ResponseResult;
import com.lxw.manage.course.client.CmsPageClient;
import com.lxw.manage.course.dao.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

/**
 *
 */
@Service
public class CourseService {

    @Autowired
    private CoursePicRepository coursePicRepository;

    @Autowired
    private CourseBaseRepository courseBaseRepository;

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private TeachplanRepository teachplanRepository;

    @Autowired
    private CourseMarketRepository courseMarketRepository;

    @Autowired
    private CmsPageClient cmsPageClient;

    @Autowired
    private CoursePubRepository coursePubRepository;
    @Autowired
    private TeachplanMediaRepository teachplanMediaRepository;

    @Value("${course-publish.dataUrlPre}")
    private String publish_dataUrlPre;
    @Value("${course-publish.pagePhysicalPath}")
    private String publish_page_physicalpath;
    @Value("${course-publish.pageWebPath}")
    private String publish_page_webpath;
    @Value("${course-publish.siteId}")
    private String publish_siteId;
    @Value("${course-publish.templateId}")
    private String publish_templateId;
    @Value("${course-publish.previewUrl}")
    private String previewUrl;
    @Transactional
    public ResponseResult addCoursePic(String courseId, String fileId) {
        if(StringUtils.isEmpty(courseId) || StringUtils.isEmpty(fileId)){
            ExceptionCast.cast(CommonCode.INIT_PARAM);
        }
        CoursePic coursePic = new CoursePic();
        coursePic.setCourseid(courseId);
        coursePic.setPic(fileId);
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Transactional
    public CoursePic findCoursePicByCourseId(String courseId) {

        Optional<CoursePic> optional = coursePicRepository.findById(courseId);
        if (!optional.isPresent()){
            ExceptionCast.cast(CommonCode.INIT_PARAM);
        }
        return optional.get();
    }

    @Transactional
    public ResponseResult deleteCoursePicById(String courseId) {
        Integer count = coursePicRepository.deleteByCourseid(courseId);
        if(count>0){
            return new ResponseResult(CommonCode.SUCCESS);
        }else {
            return new ResponseResult(CommonCode.FAIL);
        }
    }

    @Transactional
    public CourseView findCourseViewById(String id) {
        if(StringUtils.isEmpty(id)){
            ExceptionCast.cast(CommonCode.INIT_PARAM);
        }
        //获取课程基本信息
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(id);
        if (!optionalCourseBase.isPresent()){
            ExceptionCast.cast(CommonCode.INIT_PARAM);
        }

        CourseView courseView = new CourseView();
        CourseBase courseBase = optionalCourseBase.get();
        courseView.setCourseBase(courseBase);

        //获取课程图片信息
        Optional<CoursePic> optionalCoursePic = coursePicRepository.findById(id);
        if (optionalCoursePic.isPresent()){
            courseView.setCoursePic(optionalCoursePic.get());
        }

        //获取课程营销信息
        Optional<CourseMarket> courseMarketOptional = courseMarketRepository.findById(id);
        if (courseMarketOptional.isPresent()){
            courseView.setCourseMarket(courseMarketOptional.get());
        }
        //获取课程课程计划
        TeachplanNode teachplanNode = teachplanMapper.selectList(id);
        courseView.setTeachplanNode(teachplanNode);
        return courseView;
    }

    public CoursePublishResult preview(String id) {
        CmsPage cmsPage = this.makeCmsPage(id);
        //远程调用Cms服务,保存CmsPage
        CmsPageResult result = cmsPageClient.saveCmsPage(cmsPage);
        //拼接预览课程详情的url
        String path = previewUrl+result.getCmsPage().getPageId();
        CoursePublishResult coursePublishResult = new CoursePublishResult(CommonCode.SUCCESS,path);
        return coursePublishResult;
    }

    public CoursePublishResult publish(String id) {
        CmsPage cmsPage = this.makeCmsPage(id);
        //远程调用Cms服务,保存CmsPage
        CoursePublishResult coursePublishResult = cmsPageClient.postPageQuick(cmsPage);
        //如果课程发布成功,更新课程状态
        if (coursePublishResult.isSuccess()){
            CourseBase courseBase = findCourseBaseById(id);
            courseBase.setStatus("202002");
            courseBaseRepository.save(courseBase);
        }
        //把课程信息保存更新到coursePub表中
        CoursePub coursePub = this.createCoursePub(id);
        this.saveCoursePub(id,coursePub);

        return  coursePublishResult;
    }

    public CoursePub saveCoursePub(String courseId,CoursePub coursePub){
        //coursePub.setId(courseId);
        Optional<CoursePub> optional = coursePubRepository.findById(courseId);
        if(optional.isPresent()){
            CoursePub pubDb = optional.get();
            BeanUtils.copyProperties(pubDb,coursePub);
        }else {
            coursePub.setId(null);
        }
        coursePubRepository.save(coursePub);
        return coursePub;
    }

    //拼装CoursePub对象
    private CoursePub createCoursePub(String courseId){
        CoursePub coursePub = new CoursePub();
        coursePub.setId(courseId);

        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(courseId);
        if(optionalCourseBase.isPresent()){
            CourseBase courseBase = optionalCourseBase.get();
            BeanUtils.copyProperties(courseBase,coursePub);
        }

        Optional<CourseMarket> optionalCourseMarket = courseMarketRepository.findById(courseId);
        if(optionalCourseMarket.isPresent()){
            CourseMarket courseMarket = optionalCourseMarket.get();
            BeanUtils.copyProperties(courseMarket,coursePub);
        }

        Optional<CoursePic> optionalCoursePic = coursePicRepository.findById(courseId);
        if(optionalCoursePic.isPresent()){
            CoursePic coursePic = optionalCoursePic.get();
            BeanUtils.copyProperties(coursePic,coursePub);
        }

        TeachplanNode teachplanNode = teachplanMapper.selectList(courseId);
        String jsonTeachPlan = JSON.toJSONString(teachplanNode);
        coursePub.setTeachplan(jsonTeachPlan);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = simpleDateFormat.format(new Date());
        coursePub.setPubTime(dateString);
        coursePub.setTimestamp(new Date());
        return coursePub;
    }

    private CourseBase findCourseBaseById(String id){
        //根据课程Id获取课程基本信息
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(id);
        if(!optionalCourseBase.isPresent()){
           return null;
        }
        return optionalCourseBase.get();
    }
    private CmsPage makeCmsPage(String id){
        //根据课程Id获取课程基本信息
        CourseBase courseBase = findCourseBaseById(id);

        //创建CmsPage对象,并设置属性
        CmsPage cmsPage = new CmsPage();
        cmsPage.setDataUrl(publish_dataUrlPre+id);
        cmsPage.setPageAliase(courseBase.getName());
        cmsPage.setTemplateId(publish_templateId);
        cmsPage.setSiteId(publish_siteId);
//        cmsPage.setPageCreateTime(new Date());
        cmsPage.setPageName(id+".html");
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);
        cmsPage.setPageWebPath(publish_page_webpath);
        return cmsPage;
    }

    public ResponseResult saveTeachMedia(TeachplanMedia teachplanMedia) {
        //只允许给三级课程计划关联视频
        Optional<Teachplan> optional = teachplanRepository.findById(teachplanMedia.getTeachplanId());
        if (!optional.isPresent()){
            ExceptionCast.cast(CommonCode.INIT_PARAM);
        }
        Teachplan teachplan = optional.get();
        String grade = teachplan.getGrade();
        if (!"3".equals(grade)){
            ExceptionCast.cast(CommonCode.INIT_PARAM);
        }
        TeachplanMedia teachplanMedia1 = teachplanMediaRepository.save(teachplanMedia);
        return new ResponseResult(CommonCode.SUCCESS);
    }
}
